<?php

require_once 'db_conn.php';

define('LEVEL_0', 'Base Training');
define('LEVEL_1', 'Novice Frame Fitting');
define('LEVEL_2', 'Expert Frame Fitting');

import_request_variables("p", "z"); // $_POST['Q1[$var]'] becomes zQ1[$var] // $_POST['U[$var]'] becomes zU[$var]

// Validate form for pre-game questionnaire
$Q1_validation_errors = '';
function validate_q1_form() {
	global $Q1_validation_errors, $zQ1;

	if (isset($_POST['Q1'])) {
		
		$missingfields = array();
		$incorrectfields = array();
		$required = array(
				"name"					=>"Full Name",
				"age"					=>"Age",
				"gender"				=>"Gender",
				"education"				=>"Educational Qualification",
				"background"			=>"Background",
				"years_computer_usage"	=>"Years of experience in using a computer",
				"years_computer_play"	=>"Years of experience in playing computer games");

		while (list($var, $val) = each($required)) {
			if (isset($zQ1[$var]) && $zQ1[$var] != '') {

				// variable type and value validation
				if (($var == "name") && (!(is_string($zQ1[$var])) || (strlen($zQ1[$var])) < 2))
					$incorrectfields[$var] = "The name should be a string at least 2 characters long.";

				if (($var == "age") && (!(is_numeric($zQ1[$var])) || ($zQ1[$var] < 15) || ($zQ1[$var] > 70)))
					$incorrectfields[$var] = "The age should be a number between 15 and 70.";

				if (($var == "gender") && (!(is_string($zQ1[$var])) || (!(strcmp($zQ1[$var],"female")) &&
						!(strcmp($zQ1[$var],"male")))))
					$incorrectfields[$var] = "The gender should be male or female.";

				if (($var == "education") && (!(is_string($zQ1[$var])) || (!(strcmp($zQ1[$var],"highschool")) &&
						!(strcmp($zQ1[$var],"undergraduate")) && !(strcmp($zQ1[$var],"graduate")) && !(strcmp($zQ1[$var],"postgraduate")))))
					$incorrectfields[$var] = "The educational background should be one of the 4 options.";

				if (($var == "background") && (!(is_string($zQ1[$var])) || (strlen($zQ1[$var])) < 2))
					$incorrectfields[$var] = "The background should be a string at least 2 characters long.";

				if (($var == "years_computer_usage") && (!(is_numeric($zQ1[$var])) || ($zQ1[$var] < 0) || ($zQ1[$var] > 70)))
					$incorrectfields[$var] = "The years of experience in using a computer should be a number between 0 and 70.";

				if (($var == "years_computer_play") && (!(is_numeric($zQ1[$var])) || ($zQ1[$var] < 0) || ($zQ1[$var] > 70)))
					$incorrectfields[$var] = "The years of experience in playing computer games should be a number between 0 and 70.";

			} else {
				$missingfields[$var] = $val;
			}
		}
		
		if (count($missingfields)) {
			$Q1_validation_errors .= "You missed out one or more fields:<br /><ul>";
			while(list($var, $val) = each($missingfields)) {
				$Q1_validation_errors .= "<li>" . $val . "</li>";
			}
			if ($Q1_validation_errors) $Q1_validation_errors .= "</ul>";
		} elseif (count($incorrectfields)) {
			$Q1_validation_errors .= "Some of the values you filled in are incorrect:<br /><ul>";
			while(list($var, $val) = each($incorrectfields)) {
				$Q1_validation_errors .= "<li>" . $val . "</li>";
			}
			if ($Q1_validation_errors) $Q1_validation_errors .= "</ul>";
		}
		else {
			// Questionnaire 1 has been filled in
			$q1_id = insert_q1(NULL, $zQ1['name'], $zQ1['age'], $zQ1['gender'], $zQ1['education'], $zQ1['background'], $zQ1['years_computer_usage'], $zQ1['years_computer_play']);
			if ($q1_id)
				$_SESSION['Q1_ID'] = $q1_id;
		}
	}
}

// Validate form for pre-game questionnaire
$U_validation_errors = '';
function validate_user_account_form() {
	global $U_validation_errors, $zU;

	if (isset($_POST['U'])) {

		$missingfields = array();
		$incorrectfields = array();
		$required = array(
				"username"		=>"Username",
				"password"		=>"Password",
				"password_c"	=>"Password Confirmation");

		while (list($var, $val) = each($required)) {
			if (isset($zU[$var]) && $zU[$var] != '') {

				// variable type and value validation
				if (($var == "username") && (!(is_string($zU[$var])) || (strlen($zU[$var])) < 3))
					$incorrectfields[$var] = "The username should be a string at least 3 characters long.";

				if (($var == "password") && (!(is_string($zU[$var])) || (strlen($zU[$var])) < 3))
					$incorrectfields[$var] = "The password should be a string at least 3 characters long.";

				if (($var == "password_c") && (!(is_string($zU[$var])) || (strlen($zU[$var])) < 3))
					$incorrectfields[$var] = "The password confirmation should be a string at least 3 characters long.";

				if (($var == "password_c") && ((strcmp($zU['password_c'],$zU['password']))) != 0)
					$incorrectfields[$var] = "The password and password confirmation should be the same.";

			} else {
				$missingfields[$var] = $val;
			}
		}

		if (count($missingfields)) {
			$U_validation_errors .= "You missed out one or more fields:<br /><ul>";
			while(list($var, $val) = each($missingfields)) {
				$U_validation_errors .= "<li>" . $val . "</li>";
			}
			if ($U_validation_errors) $U_validation_errors .= "</ul>";
		} elseif (count($incorrectfields)) {
			$U_validation_errors .= "Some of the values you filled in are incorrect:<br />";
			while(list($var, $val) = each($incorrectfields)) {
				$U_validation_errors .= "<li>" . $val . "</li>";
			}
			if ($U_validation_errors) $U_validation_errors .= "</ul>";
		}
		else {
			// User account form has been filled in
			if (insert_user($zU['username'], $zU['password'])) {
				$_SESSION['username'] = $zU['username'];
				$_SESSION['points'] = 0;
				$_SESSION['level'] = 0;
				$_SESSION['level_description'] = LEVEL_0;
				update_username_for_q1($_SESSION['Q1_ID'], $_SESSION['username']);
				assign_face_shape_order_to_user($_SESSION['username']);
				user_login($zU['username'], $zU['password']);
			}
			else 
				$U_validation_errors .= 'The username is already taken! Try another one.';
		}
	}
}


function insert_q1($username, $name, $age, $gender, $education, $background, $yrs_computer_experience, $yrs_gaming_experience) {
	$query = sprintf( 
			"INSERT INTO `ime210-dbs`.`q1` (
				`ID` ,
				`Username` ,
				`Name` ,
				`Age` ,
				`Gender` ,
				`Education` ,
				`Background` ,
				`YrsComputerExperience` ,
				`YrsGamingExperience`
				)
			VALUES (
				NULL , '%s', '%s', %d, '%s', '%s', '%s', %d, %d
				);",
					mysql_real_escape_string($username),
					mysql_real_escape_string($name),
					$age,
					mysql_real_escape_string($gender),
					mysql_real_escape_string($education),
					mysql_real_escape_string($background),
					$yrs_computer_experience,
					$yrs_gaming_experience
	);
	
	if (mysql_query($query))
		return mysql_insert_id();
	else 
		return 0;
	
}
function insert_user($username, $password) {
	$query = sprintf(
			"INSERT INTO `ime210-dbs`.`user` (
				`Username` ,
				`Password`
				)
			VALUES (
				'%s', '%s'
				);",
			mysql_real_escape_string($username),
			mysql_real_escape_string($password)
	);
	
	return mysql_query($query); // true on success, false on error

}
function update_username_for_q1($q1_id, $username) {
	$query = sprintf(
			"UPDATE `ime210-dbs`.`q1` SET `Username` = '%s' WHERE `q1`.`ID` =%d;",
				mysql_real_escape_string($username),
				$q1_id
			);

	if (mysql_query($query)) // returns true on success and false on error
		return mysql_affected_rows(); //returns -1 if no rows affected
	else
		return 0;
}
function user_login($username, $password) {
	$query = sprintf(
			"SELECT * FROM `ime210-dbs`.`user` WHERE `Username` = '%s' AND `Password` = '%s';",
				mysql_real_escape_string($username),
				mysql_real_escape_string($password)
			);

	$result = mysql_query($query);
	if (!$result)
		return false;
	
	if (mysql_num_rows($result) == 0)
		return false;
	
	if ($row = mysql_fetch_assoc($result)) {
	    $_SESSION['username'] = $row['Username'];
	    $_SESSION['score'] = $row['Score'];
	    $_SESSION['level'] = $row['Level'];
	    $_SESSION['level_description'] = constant('LEVEL_' . $row['Level']);
	    add_to_session_face_shape_order_for_user($_SESSION['username']);
	}
	return true;
}

function insert_face_shapes_order_entries ($array) {
	$query = sprintf(
			"INSERT INTO  `ime210-dbs`.`face_shape_order` (
				`ID` ,
				`Username` ,
				`fs1` ,
				`fs2` ,
				`fs3` ,
				`fs4` ,
				`fs5` ,
				`fs6` ,
				`fs7` ,
				`fs8`
				)
				VALUES (
				NULL , NULL ,  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s',  '%s'
				);",
				mysql_real_escape_string($array[0]),
				mysql_real_escape_string($array[1]),
				mysql_real_escape_string($array[2]),
				mysql_real_escape_string($array[3]),
				mysql_real_escape_string($array[4]),
				mysql_real_escape_string($array[5]),
				mysql_real_escape_string($array[6]),
				mysql_real_escape_string($array[7])
			);
	mysql_query($query);
}

// Each player is assigned a random ordering of face shapes for the Base Training level. 
// This ordering is kept constant per player throughout the game.
function generate_face_shapes_order_entries() {
	$face_shapes_array = array("diamond", "heart", "inverted_triangle", "oval", "pear", "rectangle", "round", "square");
	
	// generate 500 entries 
	for ($i=1; $i<500; $i++) {
		shuffle($face_shapes_array);
		insert_face_shapes_order_entries($face_shapes_array);
	}
}

// Assign the next face shape ordering in line to this player, 
// and if none are available, generate a new batch of 500 face shape orderings.
function assign_face_shape_order_to_user($username) {
	do {
		$query = sprintf(
				"UPDATE face_shape_order SET Username = '%s' WHERE Username IS NULL LIMIT 1;",
				mysql_real_escape_string($username)
		);
		if (mysql_query($query))
			if (mysql_affected_rows() > 0)
				break;
		generate_face_shapes_order_entries();
	} while (true);
}

function add_to_session_face_shape_order_for_user($username) {
	$query = sprintf(
			"SELECT * FROM `ime210-dbs`.`face_shape_order` WHERE `Username` = '%s' LIMIT 1;",
			mysql_real_escape_string($username)
	);
	
	$result = mysql_query($query);
	if (!$result)
		return false;

	if ($row = mysql_fetch_assoc($result)) {
		$_SESSION['fs1'] = $row['fs1'];
		$_SESSION['fs2'] = $row['fs2'];
		$_SESSION['fs3'] = $row['fs3'];
		$_SESSION['fs4'] = $row['fs4'];
		$_SESSION['fs5'] = $row['fs5'];
		$_SESSION['fs6'] = $row['fs6'];
		$_SESSION['fs7'] = $row['fs7'];
		$_SESSION['fs8'] = $row['fs8'];
	}
	return true;	
}

function vote_face_shape($face, $face_shape) {
	$query_update = sprintf(
			"UPDATE `face_shape_vote` SET VoteCount = VoteCount + 1 WHERE Face=%d AND FaceShape='%s'",
			$face,
			mysql_real_escape_string($face_shape)
	);
	if (mysql_query($query_update))
		if (mysql_affected_rows() > 0)
			log_face_shape_vote($face, $face_shape);
	else {
		$query_insert = sprintf(
				"INSERT INTO `face_shape_vote` (Face, FaceShape, VoteCount) VALUES (%d, '%s', 1);",
					$face,
					mysql_real_escape_string($face_shape)
				);
		if (mysql_query($query_insert))
			if (mysql_affected_rows() > 0)
			log_face_shape_vote($face, $face_shape);
	}
}

function log_face_shape_vote($face, $face_shape) {
	$query = sprintf(
			"INSERT INTO  `ime210-dbs`.`face_shape_vote_history` (
				`ID` ,
				`Username` ,
				`Face` ,
				`FaceShape` ,
				`TimeStamp`
				)
				VALUES (
				NULL , '%s' , %d,  '%s',  %d
				);",
			mysql_real_escape_string($_SESSION['username']),
			$face,
			mysql_real_escape_string($face_shape),
			time()
	);
	mysql_query($query);
}

function unlock_next_level() {
	$query = sprintf(
			"UPDATE `user` SET Level = Level + 1 WHERE Username='%s'",
			mysql_real_escape_string($_SESSION['username'])
	);
	if (mysql_query($query))
		if (mysql_affected_rows() > 0) {
			$_SESSION['level']++;
			return true;
	}
	return false;
}

function update_score() {
	$new_score = $_SESSION['score'] + 10;
	$query = sprintf(
			"UPDATE `user` SET Score = %d WHERE Username='%s'",
			$new_score,
			mysql_real_escape_string($_SESSION['username'])
	);
	if (mysql_query($query))
		if (mysql_affected_rows() > 0) {
			$_SESSION['score'] = $new_score;
			if ((($_SESSION['score'] >= 500) && ($_SESSION['level'] < 1)) || (($_SESSION['score'] >= 1000) && ($_SESSION['level'] < 2)))
				unlock_next_level();
			return true;
	}
	return false;
}
?>